package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);

        //2如果不符合，返回错误信息
      if(phoneInvalid==true){
          return Result.fail("手机号格式错误");
      }
        //3.符合，生成验证码
      else {
          String code = RandomUtil.randomNumbers(4);
          //4.保存验证码到redis  有效期2分钟
//          session.setAttribute("code",code);
         stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY +phone,code,RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
          //5.发送验证码
          log.debug("发送短信验证码成功,验证码:"+code);
          //返回
          return Result.ok();
      }
      }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号
        if(RegexUtils.isPhoneInvalid(loginForm.getPhone())){
            return Result.fail("手机号格式错误");
        }
        //2.校验验证码//从redis中获取
        String code = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY +loginForm.getPhone());
        //3.不一致，报错
        if(StringUtils.isEmpty(code)){
            return Result.fail("验证码已过期");
        }
        if(!code.equals(loginForm.getCode())){
           return Result.fail("验证码错误");
        }


        //4.手机号查询用户
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,loginForm.getPhone());
        //5.查询用户是否存在
        User user = userMapper.selectOne(queryWrapper);

        if(ObjectUtils.isEmpty(user)){
            //6.不存在，创建新用户并保存
           user= createUserWithPhone(loginForm.getPhone());

        }

        //7.保存用户信息到redis中
        //7.1生成token，作为登录令牌
        String token = UUID.randomUUID().toString(true);
        //7.2将User对象转为Hash存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //7.3存储数据到redis中 ,将User转为HashMap存储
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("id",userDTO.getId().toString());
        userMap.put("nickName",userDTO.getNickName());
        userMap.put("icon",userDTO.getIcon());

        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,userMap);
        //7.4设置有效期为30分钟
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,30,TimeUnit.MINUTES);
        //8.返回给客户端
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //获得当前登录的用户
        Long userId = UserHolder.getUser().getId();
        //获取当前日期
        LocalDateTime now = LocalDateTime.now();
        //拼接key
        String KeySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key=RedisConstants.USER_SIGN_KEY+userId+KeySuffix;
        //获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //写入redis SETBIT key offset 1
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {

        //获得当前登录的用户
        Long userId = UserHolder.getUser().getId();
        //获取当前日期
        LocalDateTime now = LocalDateTime.now();
        //拼接key
        String KeySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key=RedisConstants.USER_SIGN_KEY+userId+KeySuffix;
        //获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //获取本月截止今天为止的所有签到记录,返回的是一个十进制的数字
        List<Long> result = stringRedisTemplate.opsForValue().
                bitField(key, BitFieldSubCommands.create().
                        //get方式请求,无符号位，当前是这个月的第几天就获得多少个符号位
                        get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        //从第一个位置开始获取
                        .valueAt(0));
        if(result==null||result.isEmpty()){
            //没有签到结果
            return Result.ok(0);
        }
        Long num = result.get(0);
        if(num==0||num==null){
            //转化为十进制没有结果
            return Result.ok(0);
        }
        //循环遍历
        int count=0;
        while(true) {
            //让这个数字与1做与运算，得到数字的最后一个bit位
            if((num&1)==0){
                //判断bit位是否为0，说明未签到
                break;

            }
            else {
                //如果不为0，说明已签到，计时器加1
                 count++;

            }
            //把数字右移一位，抛弃最后一位，继续下一个比特位
            num >>>=1;



        }
        return Result.ok(count);
    }

    private User createUserWithPhone(String phone) {
        User user=new User();
        user.setPhone(phone);
        user.setNickName("fengge_"+RandomUtil.randomString(8));
        //2.保存用户
        save(user);
        return user;
    }


}
